const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const fileExtensions =
	'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|ico)$';

module.exports = {
	target: 'web',
	mode: 'production',
	devtool: 'source-map',

	entry: {
		main: [path.join(process.cwd(), 'browser')],
	},

	output: {
		filename: '[name].[chunkhash].js',
		chunkFilename: '[name].[chunkhash].js',
		publicPath: '/assets/',
		path: path.join(process.cwd(), 'static/assets'),
	},

	resolve: {
		extensions: ['.mjs', '.js', '.jsx'],
		alias: {
			'package.json': path.join(process.cwd(), 'package.json'),
		},
	},

	resolveLoader: {
		modules: [
			...module.paths,
			path.join(__dirname, '../../../node_modules'),
			path.join(process.cwd(), 'node_modules'),
			'node_modules',
		],
	},

	node: {
		__dirname: true,
		__filename: true,
	},

	optimization: {
		splitChunks: {
			chunks: 'all',
			name: false,
		},
		runtimeChunk: {
			name: 'manifest',
		},
	},

	module: {
		rules: [
			{
				test: new RegExp(fileExtensions),
				loader: 'url-loader',
				exclude: [/SvgIcon/],
				options: {
					limit: 20000,
				},
			},
			{
				test: /\.css$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader'],
			},
		],
	},

	plugins: [
		new webpack.DefinePlugin({
			'process.env.NODE_ENV': JSON.stringify('production'),
		}),
		new HtmlWebpackPlugin({
			inject: true,
			filename: '../index.html',
			template: path.join(__dirname, '/template.html'),
		}),

		new MiniCssExtractPlugin({
			filename: '[contenthash].css',
			chunkFilename: '[contenthash].css',
		}),
		new OptimizeCSSAssetsPlugin(),
	],
};
